package com.is2.patchinglife.util;

import java.util.Collections;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.graphics.Typeface;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.TextView;

import com.facebook.Session;
import com.facebook.SessionState;
import com.is2.patchinglife.R;
import com.is2.patchinglife.activity.ProfileActivity;
import com.is2.patchinglife.manager.ActivityManager;
import com.is2.patchinglife.manager.FacebookManager;
import com.is2.patchinglife.manager.LocalDataManager;
 
public class ExpandableListAdapter extends BaseExpandableListAdapter {
 
    private Activity context;					// context reference
    private List<String> trophyKeys;			// list of trophy keys
    private int lastExpandedGroupPosition;		// last expanded element ID
    private final int childNum = 1;				// children number for each list element
    boolean firstExec = true;					// flag to avoid publishing more than once
    
    /** Guest callback, invoked at publishing **/
    private Session.StatusCallback guestCallback = new Session.StatusCallback() {
    	@Override
    	public void call(Session session, SessionState state, Exception exception) {
    		
    		// open facebook session
    		FacebookManager.initFacebookSession();
    		
    		if(firstExec){
    			
	    		if(session.isOpened()){		// only guest
	    			if(LocalDataManager.getUser().compareTo("GUEST")==0){
		    			// publish on facebook [general message]
		    			FacebookManager.publishSomething(com.is2.patchinglife.manager.ActivityManager
										.getInstance().get("TrophyActivity"), 
		    							"PatchingLIFE",
		    							"Download PatchingLife!", 
		    							"I've just won a trophy on patchingLIFE! What about you? What are you waiting for? Even you can win all our unbelievable trophies and challange your friends. Download it now for FREE! PatchingLIFE: share your life!",
		    							"http://www.patchinglife.altervista.org/img/default_icon.png", 
		    							"http://www.patchinglife.altervista.org/img/default_icon.png",
		    							true);
		    			
	    			}else{

	    			FacebookManager.initFacebookSession();
	    			// publish on facebook as usert auth
					FacebookManager.publishSomething(com.is2.patchinglife.manager.ActivityManager
							.getInstance().get("TrophyActivity"), 
							"Trophy earned",
							LocalDataManager.getName(trophyKey), 
							LocalDataManager.getDesc(trophyKey), 
							"http://www.patchinglife.altervista.org/img/"+LocalDataManager.getImage(trophyKey)+".png",
							"http://www.patchinglife.altervista.org/img/"+LocalDataManager.getImage(trophyKey)+".png",
							false);
	    			}
	    			firstExec = false;
	    		}else if (exception!=null){
	    			
	    			Session.setActiveSession(new Session(LocalDataManager.getContext()));
	    		}
    		}else{
    			firstExec = true;
    		}
    	}
    };
    
    
    /** Constructor **/
    public ExpandableListAdapter(Activity _context) {
        this.context = _context;														// set context
        this.trophyKeys = Collections.list(LocalDataManager.getGotTrophy().keys());		// get trophy keys
    }
    
    
    /** Returns the KEY (String) associated to ID (int) **/
    public String getTrophyKey(int _pos){return trophyKeys.get(_pos);};
    
    
    // MANDATORY METHODS
    public Object getGroup(int groupPosition){return null;}
    public Object getChild(int groupPosition, int childPosition){return null;}
    
    public long getGroupId(int groupPosition){return groupPosition;}
    public long getChildId(int groupPosition, int childPosition){return childPosition;}
 
    public int getGroupCount(){return trophyKeys.size();}
    public int getChildrenCount(int groupPosition){return childNum;}
    
    public boolean hasStableIds(){return true;}
    public boolean isChildSelectable(int groupPosition, int childPosition){return true;}
    
    /** Needed to create a Group element **/
    public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
    	
    	String trophyKey = trophyKeys.get(groupPosition); 	// get the key associated to group

    	// inflate group layout
    	if (convertView == null) {
            LayoutInflater infalInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = infalInflater.inflate(R.layout.trophy_group,null);
        }
        
    	// set trophy name
        TextView tName = (TextView) convertView.findViewById(R.id.trophyDesc);
        String name = LocalDataManager.getName(trophyKey);
        tName.setTypeface(null, Typeface.BOLD_ITALIC);
        tName.setText(name);
        
        // set trophy image
        String image = LocalDataManager.getImage(trophyKey);
        ImageView tIcon = (ImageView) convertView.findViewById(R.id.trophyIcon);
        boolean gotIT = LocalDataManager.getGotIT(trophyKey);
        if(gotIT){
        	int ID = context.getResources().getIdentifier(image,"drawable", context.getPackageName());
        	tIcon.setImageResource(ID);
        }else
        	tIcon.setImageResource(R.drawable.default_icon);
        
        return convertView;
    }
    
    
    /** Invoked when a Group element is selected **/ 
    public void onGroupExpanded(int groupPosition){
    	
    	// expand/collapse logic
    	ExpandableListView expList;
    	if(LocalDataManager.getGotIT(getTrophyKey(groupPosition))){							// if gotIT ...
	        if(groupPosition != lastExpandedGroupPosition){									// if current expanded == old expanded, do nothing
	            expList = (ExpandableListView) context.findViewById(R.id.trophyExpList);
	        	expList.collapseGroup(lastExpandedGroupPosition);							// collapse last expanded group
	        }
    		lastExpandedGroupPosition = groupPosition;										// update last expanded group ID
    	
    	}else{
	    	expList = (ExpandableListView) context.findViewById(R.id.trophyExpList);		// if !gotIT ...
        	expList.collapseGroup(groupPosition);											// ... do nothing [collapse itself]
	    }
	    
        super.onGroupExpanded(groupPosition);
    }
    
    private String trophyKey;
    /** Needed to create a Child element **/
    public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent){
    	
    	trophyKey = trophyKeys.get(groupPosition);	 	// get the key associated to group
    	
    	// inflate child layout
        if (convertView == null){
        	LayoutInflater inflater = context.getLayoutInflater();
            convertView = inflater.inflate(R.layout.trophy_child, null);
        }
 
        // set description
        TextView desc_tw = (TextView) convertView.findViewById(R.id.trophyDesc);
        desc_tw.setText(LocalDataManager.getDesc(trophyKey));
        
        // set image
        String image = LocalDataManager.getImage(trophyKey);
        ImageView image_iw = (ImageView) convertView.findViewById(R.id.trophyBig);
        int ID = context.getResources().getIdentifier(image,"drawable", context.getPackageName());
    	image_iw.setImageResource(ID);
        
        // set date
    	String date = LocalDataManager.getDate(trophyKey);
        TextView date_tw = (TextView) convertView.findViewById(R.id.gotDate);
        date_tw.setText("DATE: "+date);
        
        /** START FB **/
        // setting FB share button
        ImageView fb_button = (ImageView)convertView.findViewById(R.id.fb);
        fb_button.setOnClickListener(new View.OnClickListener() {	
			@Override
			public void onClick(View v){
				
				ActivityManager.executeButtonEffects();		// execute button effects
				
				// authenticated user
				if(LocalDataManager.getUser().compareTo("GUEST")!=0){
					if(!Session.getActiveSession().isOpened()){
					// login on facebook
					FacebookManager.loginFacebook(
							com.is2.patchinglife.manager.ActivityManager.getInstance().get("TrophyActivity"),
							guestCallback,
							null);
					}else{
					// publish on facebook as usert auth
					FacebookManager.publishSomething(com.is2.patchinglife.manager.ActivityManager
							.getInstance().get("TrophyActivity"), 
							"Trophy earned",
							LocalDataManager.getName(trophyKey), 
							LocalDataManager.getDesc(trophyKey), 
							"http://www.patchinglife.altervista.org/img/"+LocalDataManager.getImage(trophyKey)+".png",
							"http://www.patchinglife.altervista.org/img/"+LocalDataManager.getImage(trophyKey)+".png",
							false);
					}
				// guest user
				}else{
					FacebookManager.loginFacebook(
							com.is2.patchinglife.manager.ActivityManager.getInstance().get("TrophyActivity"),
							guestCallback,
							null);
				}
				
			}
			
		});

        // set GooglePlus link button
        ImageView tw_button = (ImageView)convertView.findViewById(R.id.tw);
        tw_button.setOnClickListener(new View.OnClickListener() {
        	@Override
        	public void onClick(View v) {

        		ActivityManager.executeButtonEffects();		// execute button effects
        		ActivityManager.comingSoonDialog(ActivityManager.getInstance().get("TrophyActivity"));

        	}
        });
        // set GooglePlus link button
        ImageView gp_button = (ImageView)convertView.findViewById(R.id.gp);
        gp_button.setOnClickListener(new View.OnClickListener() {
        	@Override
        	public void onClick(View v) {

        		ActivityManager.executeButtonEffects();		// execute button effects
        		ActivityManager.comingSoonDialog(ActivityManager.getInstance().get("TrophyActivity"));

        	}
        });
 
        return convertView;
    }
    /** END FB **/
}